import 'dart:convert';
import 'dart:ffi';

import 'package:chathouse/pages/base/base.dart';
import 'package:chathouse/pages/expert/wallet_page.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/public/NetworkImageBrowser.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../chat/chat_page.dart';
import '../../model/client_search_model.dart';
import '../../model/masterplateModel.dart';
import '../../model/template_serivce_model.dart';
import '../../public/empty_widget.dart';
import '../../public/event_bus.dart';
import '../widgets/down_item.dart';
import '../widgets/down_menu_items.dart';

class AddMasterpl extends StatefulWidget {
  Rows? item;

  AddMasterpl(this.item, {Key? key}) : super(key: key);

  @override
  _AddMasterplState createState() => _AddMasterplState();
}

class _AddMasterplState extends State<AddMasterpl> {
  TextEditingController tagControl = TextEditingController();
  ScrollController scrollController = ScrollController();
  TemplateServiceModel? clientSearchModel;
  List<CMenuItem>? dataList;

  List<String> imageUrls = [];
  String seleValue = "";
  int idx = -1;

  String changeImageUrl = "";

  @override
  void initState() {
    super.initState();
    tagControl.text = widget.item?.templateComment ?? "";
    seleValue = widget.item?.serviceName ?? "";
    imageUrls = (widget.item?.templateImg ?? "").split(",");
    Obj.showLoading();
    Apis.templateServicelist({}).then((response) {
      Obj.dismissLoading();
      var data = response?.data;
      if (data["code"] != 200) {
        return;
      }
      clientSearchModel = TemplateServiceModel.fromJson(data);
      dataList = getPreviousSixMonths();
      if (seleValue.isNotEmpty) {
        int number = clientSearchModel?.rows?.length ?? 0;
        for (int i = 0; i < number; i++) {
          TemplateServiceItem data = clientSearchModel!.rows![i];
          if (data.serviceName == seleValue) {
            idx = i;
          }
        }
      }
      setState(() {});
    }).catchError((error) {
      Obj.dismissLoading();
    });
  }

  List<CMenuItem> getPreviousSixMonths() {
    List<CMenuItem> previousMonths = [];
    int number = clientSearchModel?.rows?.length ?? 0;
    for (int i = 0; i < number; i++) {
      TemplateServiceItem data = clientSearchModel!.rows![i];
      CMenuItem item = CMenuItem(
          label: data.serviceName ?? "", value: data.serviceName ?? "");
      previousMonths.add(item);
    }

    return previousMonths;
  }

  void changeSelectValue(value) {
    seleValue = value;
    int number = clientSearchModel?.rows?.length ?? 0;
    for (int i = 0; i < number; i++) {
      TemplateServiceItem data = clientSearchModel!.rows![i];
      if (data.serviceName == value) {
        idx = i;
      }
    }
    setState(() {});
  }

  add() {
    if (idx == -1) {
      ToastUtil.showToast("選擇模本服務");
      return;
    }
    if (tagControl.text.isEmpty) {
      ToastUtil.showToast("輸入模本內容");
      return;
    }
    List imgs = [];
    imageUrls.forEach((element) {
      if(element.isNotEmpty) {
        imgs.add(element);
      }
    });
    Obj.showLoading();
    Apis.addTemplate({
      "templateComment": tagControl.text,
      "serviceId": clientSearchModel!.rows![idx].serviceId,
      "templateImg": imgs.join(',')
    }).then((response) {
      Obj.dismissLoading();
      Get.back();
      eventBus.fire(UpdateMemberInfo());
    }).onError((error, stackTrace) {
      Obj.dismissLoading();
    });
  }

  edit() {
    if (idx == -1) {
      ToastUtil.showToast("選擇模本服務");
      return;
    }
    if (tagControl.text.isEmpty) {
      ToastUtil.showToast("輸入模本內容");
      return;
    }
    List imgs = [];
    imageUrls.forEach((element) {
      if(element.isNotEmpty) {
        imgs.add(element);
      }
    });
    Obj.showLoading();
    Apis.editTemplate({
      "templateComment": tagControl.text,
      "templateId": widget.item?.templateId ?? "",
      "serviceId": clientSearchModel!.rows![idx].serviceId,
      "version": widget.item?.version,
      "templateImg": imgs.join(',')
    }).then((response) {
      Obj.dismissLoading();
      Get.back();
      eventBus.fire(UpdateMemberInfo());
    }).onError((error, stackTrace) {
      Obj.dismissLoading();
    });
  }

  List<Widget> getSubWidgets() {
    List<Widget> subWidgets = [];
    for (var element in imageUrls) {
      if (element.isNotEmpty) {
        subWidgets.add(getImageWidget(element));
      }
    }
    if (subWidgets.length < 3) {
      subWidgets.add(getAddWidget());
    }

    return subWidgets;
  }

  Widget getImageWidget(String url) {
    double itemW = (1.sw - 32.w * 2 - 16.w * 2) / 3.0 - 0.1;
    return ClipRRect(
      child: Container(
        width: itemW,
        height: itemW,
        decoration: BoxDecoration(
            color: MyColors.gary_230230230,
            borderRadius: BorderRadius.circular(20.w)),
        child: ImageUtils.image(url,
            imageType: ImageType.NETWORK,
            width: itemW,
            height: itemW,
            key: UniqueKey()),
      ),
      borderRadius: BorderRadius.circular(20.w),
    ).setOnClickListener(() {
      // changeImageUrl = url;
      imageUrls.remove(url);
      setState(() {});
      // onAddImage();
    });
  }

  Widget getAddWidget() {
    double itemW = (1.sw - 32.w * 2 - 16.w * 2) / 3.0 - 0.1;
    return Container(
      width: itemW,
      height: itemW,
      decoration: BoxDecoration(
          color: MyColors.gary_230230230,
          borderRadius: BorderRadius.circular(20.w)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ImageUtils.image(Res.image_pick_add, width: 51.w, height: 51.w),
          SizedBox(height: 6.w),
          Text(
            "選擇照片",
            style: getTextStyle(16.sp, color: MyColors.brow_25511377),
          ),
        ],
      ),
    ).setOnClickListener(() {
      onAddImage();
    });
  }

  void onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
              width: double.infinity,
              height: 60.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          width: 1.0.w, color: MyColors.gary_149149149))))
              .setOnClickListener(() {
            Get.back(result: 1);
          }),
          Text(
            "相機",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
            alignment: Alignment.center,
            width: double.infinity,
            height: 60.w,
          )
              .setOnClickListener(() {
            Get.back(result: 2);
          }),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    if (imgData != null) {
      Obj.showLoading();
    }
    Map result;
    String? url;
    Apis.uploadFile(imgData!, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  if (imageUrls.length < 4)
                    {
                      imageUrls.add(url!),
                    },
                  setState(() {}),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        appBar: getAppBar(title: "報價單模本"),
        body: Container(
          padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 24.w),
          child: ListView(
            children: [
              SizedBox(
                height: 20.w,
              ),
              Text("選擇服務",
                  style: TextStyle(
                      color: Styles.c_191919,
                      fontWeight: FontWeight.w500,
                      fontSize: 24.w)),
              SizedBox(
                height: 10.w,
              ),
              Container(
                alignment: Alignment.center,
                height: 44.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.w),
                  border:
                      Border.all(color: MyColors.gary_158157157, width: 1.2.w),
                ),
                child: SelectWidget(
                        items: List.generate(dataList?.length ?? 0, (index) {
                          return dataList![index];
                        }),
                        value: seleValue,
                        isService: true,
                        valueChanged: changeSelectValue,
                      ),
              ),
              SizedBox(
                height: 20.w,
              ),
              Text("模本內容",
                  style: TextStyle(
                      color: Styles.c_191919,
                      fontWeight: FontWeight.w500,
                      fontSize: 24.w)),
              SizedBox(
                height: 10.w,
              ),
              Container(
                // height: INPUT_ITEM_HEIGHT.w,
                height: 240.w,
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(16.w),
                  border:
                      Border.all(color: MyColors.gary_158157157, width: 1.2.w),
                ),
                child: 
                MyTextFieldwScrollBar(tagControl: tagControl, scrollController: scrollController,),
              ),
              SizedBox(
                height: 20.w,
              ),
              Text(
                "最多3張圖片(點擊圖片刪除)",
                style: getTextStyle(20.sp,
                    color: Styles.c_999, fontType: FontType.BOLD),
              ),
              SizedBox(
                height: 16.w,
              ),
              Wrap(
                spacing: 16.w,
                runSpacing: 16.w,
                children: getSubWidgets(),
              ),
              SizedBox(
                height: 40.w,
              ),
              InkWell(
                onTap: () {
                  if (widget.item == null) {
                    add();
                  } else {
                    edit();
                  }
                },
                child: Container(
                    alignment: Alignment.center,
                    child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 80.w, vertical: 12.w),
                        decoration: BoxDecoration(
                            color: Styles.mainColor,
                            borderRadius: BorderRadius.circular(Styles.magin_16)),
                        child: Text(
                          widget.item == null ? "新增模本" : "儲存",
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                              fontSize: 20.w),
                        ))),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class MyTextFieldwScrollBar extends StatelessWidget {
  const MyTextFieldwScrollBar({
    Key? key,
    required this.tagControl, required this.scrollController,
  }) : super(key: key);

  final TextEditingController tagControl;
  final ScrollController scrollController;

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      controller: scrollController,
      child: TextField(
        keyboardType: TextInputType.multiline,
        maxLength: 250,
        style: getTextStyle(20.sp, color: Colors.black),
        maxLines: 15,
        onChanged: (val) {
          // widget.onTextChange!(val);
        },
        controller: tagControl,
        // textInputAction: TextInputAction.done,
        textInputAction: TextInputAction.newline,
        onEditingComplete: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        decoration: InputDecoration(
          hintText: "",
          hintStyle:
              getTextStyle(16.sp, color: MyColors.gary_210210210),
          border: InputBorder.none,
        ),
      ),
    );
  }
}
